<template applyPuton>
  <a-modal width="1150px" title="投放" :visible="value" :maskClosable="false" @cancel="onCancel">
    <a-spin tip="提交中..." :spinning="isSubLoading">
      <a-row :gutter="20" style="height:475px;overflow-y:scroll;">
        <a-col :span="16" class="table-wapper">
          <put-in-info :dataObject="getInfo"></put-in-info>
          <div class="table-box">
            <div class="flex table-box-title">
              <a-icon type="history" :style="{ fontSize: '18px' }" />
              <p>主播历史合作记录</p>
            </div>
            <div class="flex table-box-filter">
              <div>主播：<a-input-search v-model="search.keyWord" @pressEnter="searchHistory" style="width:240px;" placeholder="请输入主播名称/主播ID/视频ID"></a-input-search></div>
              <div class="flex">
                <a-button class="border-radious-2" type="primary" style="background:#1D6FE9;border-color:#1D6FE9;margin-right:8px;" @click="clickSearchHistory">搜索</a-button>
                <a-button class="border-radious-2 color-333" style="background:#E5E5E5;border-color:#E5E5E5;" @click="reSet">重置</a-button>
              </div>
            </div>

            <a-table :columns="tableColumns" :pagination="false" :loading="hostHistoryLoading" :data-source="dataSource" :scroll="{ x: 600, y: 200 }">
              <!-- 主播信息 -->
              <template slot="id" slot-scope="status, record">
                <p>主播ID：{{ record.id }}</p>
                <p>主播名称：{{ record.nickName }}</p>
              </template>
            </a-table>
            <!-- 分页 -->
            <div class="paging-container puton-paging-container">
              <a-pagination
                :pageSize="search.pageSize"
                v-model="search.pageIndex"
                :total="pagination.total"
                showQuickJumper
                showLessItems
                :showTotal="(total) => `共 ${total} 条`"
                style="margin: 10px auto;"
                @change="handlePageChange"
              />
            </div>
          </div>
        </a-col>
        <a-col :span="8" class="form-box">
          <a-form-model ref="putInModalForm" :model="putInModalForm" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
            <a-form-model-item label="站点" prop="locationId" :rules="[{ required: true, message: '请输入关键字选择站点', trigger: 'blur' }]">
              <!-- @search="getAreaLocation($event)" -->
              <a-select
                show-search
                :allowClear="true"
                :showArrow="false"
                placeholder="请输入关键字选择站点"
                @search="getAreaLocation(configInfo.areaId, $event)"
                v-model="putInModalForm.locationId"
                @change="selectLoction"
                :filter-option="filterOption"
              >
                <a-spin v-if="userLoading" slot="notFoundContent" size="small" />
                <a-select-option v-for="(item, index) in allLocation" :key="index" :locationName="item.city" :value="item.id">{{ item.city }}</a-select-option>
              </a-select>
            </a-form-model-item>
            <a-form-model-item label="产品" prop="productId" :rules="[{ required: true, message: '请选择产品', trigger: 'blur' }]">
              <a-select
                @search="getProductList"
                v-model="putInModalForm.productId"
                @change="selectProduct"
                :showArrow="false"
                show-search
                :filter-option="false"
                allow-clear
                placeholder="请输入产品搜索"
              >
                <a-spin v-if="userLoading" slot="notFoundContent" size="small" />
                <a-select-option v-for="(item, index) in allProduct" :productTitle="item.productTitle" :itemsList="item.productItemList" :key="index" :value="item.productId">{{
                  item.productTitle
                }}</a-select-option>
              </a-select>
            </a-form-model-item>
            <a-form-model-item label="套餐" prop="productItemId" :rules="[{ required: true, message: '请选择套餐', trigger: 'blur' }]">
              <a-select show-search :allowClear="true" placeholder="请选择套餐" v-model="putInModalForm.productItemId" @change="selectProductiItem" :filter-option="filterOption">
                <a-spin v-if="userLoading" slot="notFoundContent" size="small" />
                <a-select-option v-for="(item, index) in productItemList" :key="index" :itemName="item.productItemTitle" :value="item.productItemId">{{ item.productItemTitle }}</a-select-option>
              </a-select>
            </a-form-model-item>
            <a-form-model-item label="视频链接" prop="videoUrl" :rules="[{ required: true, message: '请输入视频链接', trigger: 'blur' }]">
              <a-input v-model="putInModalForm.videoUrl" :maxLength="50" placeholder="请输入视频链接"></a-input>
            </a-form-model-item>
            <a-form-model-item
              label="主播抖音号"
              prop="dyNo"
              :rules="[
                { required: true, message: '请输入主播抖音号', trigger: 'blur' },
                {
                  pattern: /^[a-zA-Z0-9_.]*$/,
                  message: '抖音号格式有误',
                  trigger: 'blur'
                }
              ]"
            >
              <a-input v-model="putInModalForm.dyNo" :maxLength="20" placeholder="请输入主播抖音号"></a-input>
            </a-form-model-item>
            <a-form-model-item
              label="投放金额"
              prop="money"
              :rules="[
                { required: true, trigger: 'blur', message: '请输入投放金额' },
                {
                  pattern: /^\d+(\.\d+)?$/,
                  message: '金额格式有误',
                  trigger: 'blur'
                }
              ]"
            >
              <a-input v-model="putInModalForm.money" placeholder="请输入投放金额" :maxLength="10"></a-input>
            </a-form-model-item>
            <a-form-model-item label="投放时间" prop="putTime" :rules="[{ required: true, message: '请选择投放时间', trigger: 'change' }]">
              <a-date-picker style="width:100%;" @change="changeTime" v-model="putInModalForm.putTime" />
            </a-form-model-item>
          </a-form-model>
          <!-- <put-in-form :dataObject.sync="getModalForm"></put-in-form> -->
        </a-col>
      </a-row>
    </a-spin>
    <!-- 操作 -->
    <template slot="footer">
      <template style="display:flex;justify-content: center;">
        <a-button @click="onCancel" class="gray-btn border-radious-2 color-333">取消</a-button>
        <a-button type="primary" style="background:#1D6FE9;margin-left:8px;" @click="submitApply">确认</a-button>
      </template>
    </template>
  </a-modal>
</template>
<script>
import { getCommonApiSearch } from '@/service'
import { hostHistoryList, djMoneyPutUrl, allProductListUrl, locationArealUrl } from '@/service/djService'
import debounce from 'lodash/debounce'
import putInInfo from './childComponents/putInInfo'
import moment from 'moment'
// import putInForm from './childComponents/putInForm'
import { douJiaColumn } from '../column'
const g = function(item = {}) {
  return {
    douApplyId: item.douApplyId || 0,
    dyNo: item.dyNo || '',
    id: item.id || 0,
    location: item.location || '',
    locationId: item.locationId || undefined,
    money: item.money ? (item.money / 100).toFixed(2) : '',
    productId: item.productId || undefined,
    productItemId: item.productItemId || undefined,
    productItemName: item.productItemName || '',
    productName: item.productName || '',
    videoUrl: item.videoUrl || '',
    putTime: item.putTime ? moment(item.putTime).format('YYYY-MM-DD') : undefined
  }
}

export default {
  name: 'applyPuton',
  props: {
    type: {
      type: Number,
      default: 0
    },
    value: {
      type: Boolean,
      default: false
    },
    getInfo: {
      type: Object,
      default: () => {}
    },
    douApplyId: {
      type: String | Number,
      default: ''
    },
    configInfo: {
      type: Object,
      default: () => {}
    }
  },
  watch: {
    getInfo(val) {
      console.log(val)
      //   this.putInModalForm = detailInfo
    },
    configInfo(val) {
      console.log(val)
      const { areaId = 0 } = val || {}
      this.getAreaLocation(areaId)
    }
  },
  components: { putInInfo },
  data() {
    this.getProductList = debounce(this.getProductList, 800)
    return {
      userLoading: false,
      allUser: [],
      isSubLoading: false,
      hostHistoryLoading: false,
      // table数据查询条件
      search: {
        pageIndex: 1,
        pageSize: 10,
        keyWord: ''
      },
      pagination: {
        total: 0
      },
      // TABLE LIST
      dataSource: [],
      tableColumns: douJiaColumn.hostCooperaeHistory || [],
      putInModalForm: g({}),
      allLocation: [],
      allProduct: [],
      selectSearch: {
        pageIndex: 1,
        pageSize: 10,
        keyWord: '',
        locationId: ''
      },
      productItemList: []
    }
  },
  methods: {
    moment,
    // 站点列表
    getAreaLocation(param1 = 0, param2 = '') {
      locationArealUrl({ configId: param1, city: param2, admin: 1 })
        .then((res = []) => {
          this.allLocation = res
          if (res.length === 0) {
            this.allLocation = []
          }
        })
        .catch((err) => {
          console.log(err)
        })
    },
    getLocationList(e) {
      if (!e) {
        return
      }
      this.userLoading = true
      getCommonApiSearch({ keywords: e })
        .then((res) => {
          console.log(res)
          this.allLocation = res
        })
        .finally(() => {
          this.userLoading = false
        })
        .catch(() => {
          this.userLoading = false
        })
    },
    // 产品列表
    async getProductList(keyWord = '') {
      console.log(keyWord)
      if (!keyWord) {
        return
      }
      this.userLoading = true
      this.selectSearch.keyWord = keyWord
      await allProductListUrl(this.selectSearch).then((res = []) => {
        this.allProduct = res
        this.userLoading = false
      })
    },
    selectProduct(e, option = {}) {
      const { data = {} } = option || {}
      this.productItemList = data.attrs && data.attrs.itemsList.length > 0 ? data.attrs.itemsList : []
      this.putInModalForm.productName = data.attrs && data.attrs.productTitle ? data.attrs.productTitle : ''
    },
    selectLoction(e, option) {
      const { data = {} } = option || {}
      this.putInModalForm.location = data.attrs && data.attrs.locationName ? data.attrs.locationName : ''
    },
    selectProductiItem(e, option) {
      console.log(e, option)
      const { data = {} } = option || {}
      this.putInModalForm.productItemName = data.attrs && data.attrs.itemName ? data.attrs.itemName : ''
    },
    searchHistory(value = {}) {
      const { target = {} } = value
      console.log(value)
      if (!target._value) {
        this.$messageSend.error('请输入主播名称/主播ID/视频ID')
        return
      }
      this.search.keyWord = target._value
      this.getHostHistory()
    },
    clickSearchHistory() {
      if (!this.search.keyWord) {
        this.$messageSend.error('请输入主播名称/主播ID/视频ID')
        return
      }
      this.getHostHistory()
    },
    async getHostHistory() {
      this.hostHistoryLoading = true
      await hostHistoryList(this.getParams())
        .then((res = {}) => {
          console.log(res)
          this.hostHistoryLoading = false
          const { douJAgentListData = [], total = 0 } = res
          this.dataSource = douJAgentListData || []
          this.pagination.total = total
        })
        .catch(() => {
          this.hostHistoryLoading = false
        })
    },
    // 拿参数
    getParams() {
      const { pageIndex = 1, pageSize, keyWord = '' } = this.search
      return {
        pageIndex,
        pageSize,
        keyWord
      }
    },
    /**
     * 分页
     * @param {number} num 当前页码
     * @returns {void}
     */
    handlePageChange(num) {
      this.search.pageIndex = num
      // this.setPath(this.getParams())
      this.getHostHistory()
    },
    onCancel() {
      this.$emit('input', false)
      this.putInModalForm = g()
      this.search.keyWord = ''
      this.clearForm()
    },
    clearForm() {
      let form = this.$refs.putInModalForm
      if (form && form.clearValidate) {
        this.$nextTick(() => {
          form.clearValidate()
        })
      }
    },
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    changeTime(e) {
      console.log(e)
    },
    reSet() {
      this.search.keyWord = ''
      this.getHostHistory()
    },
    submitApply() {
      console.log(this.putInModalForm, this.douApplyId)
      const { money = 0, putTime = '' } = this.putInModalForm || {}
      const { availableMoney = 0 } = this.getInfo
      if (money * 100 > availableMoney) {
        this.$messageSend.error('可投放金额不足')
        return
      }
      console.log(1)
      this.$refs.putInModalForm.validate((valid, obj = {}) => {
        if (valid) {
          this.isSubLoading = true

          const params = { ...this.putInModalForm, money: money * 100, douApplyId: this.douApplyId, putTime: moment(putTime).format('YYYY-MM-DD hh:mm:ss') }
          djMoneyPutUrl(params)
            .then((res) => {
              this.$emit('callback')
              this.onCancel()
            })
            .finally(() => {
              // this.$messageSend.success('提交成功')
              this.isSubLoading = false
            })
            .catch(() => {
              this.isSubLoading = false
            })
        }
      })
    }
  }
}
</script>
<style scoped lang="scss">
/deep/ .ant-modal-header {
  border-bottom: 1px solid transparent !important;
}
/deep/ .ant-modal-body {
  padding-top: 0;
}
/deep/ .ant-modal-footer {
  box-shadow: 0px 2px 2px 0px rgba(0, 0, 0, 0.02), inset 0px -1px 0px 0px #f5f5f5;
}
/deep/ .ant-form-item {
  margin-bottom: 18px;
}
.flex {
  display: flex;
}
.table-box,
.form-box {
  background: #f8f8f8;
  border-radius: 4px;
  padding: 16px;
}
.form-box {
  height: 100%;
}
.table-wapper {
  height: 100%;
  display: flex;
  flex-direction: column;
  // justify-content: space-between;
}
.table-box {
  &-filter {
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
  }
  &-title {
    p {
      font-size: 16px;
      font-weight: bold;
      color: #333333;
      margin: -3px 0 8px 5px;
    }
  }
}
.puton-paging-container {
  padding-right: 10px;
}
p {
  font-size: 13px;
  margin-bottom: 5px;
}
</style>
